package com.wits.util;

import android.content.Context;
import android.net.wifi.ScanResult;
import android.net.wifi.WifiConfiguration;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by chuanjiang.zh on 2016-09-11.
 */

public class WifiAdmin {
    // 定义WifiManager对象
    private WifiManager mWifiManager;
    // 定义WifiInfo对象
    private WifiInfo mWifiInfo;
    // 扫描出的网络连接列表,ScanResult主要用来描述已经检测出的接入点，包括介入点的地址，介入点的名称，身份认证，频率，信号强度等信息
    private List<ScanResult> mWifiList;
    // 网络连接列表
    private List<WifiConfiguration> mWifiConfiguration;
    // 定义一个WifiLock
    WifiManager.WifiLock mWifiLock;

    // 构造器
    public WifiAdmin(Context context) {
        // 取得WifiManager对象
        mWifiManager = (WifiManager) context
                .getSystemService(Context.WIFI_SERVICE);
        // 取得WifiInfo对象
        mWifiInfo = mWifiManager.getConnectionInfo();
    }

    // 打开WIFI
    public void openWifi() {
        if (!mWifiManager.isWifiEnabled()) {
            mWifiManager.setWifiEnabled(true);
            System.out.println("wifi打开成功!");
        }
        // if (mWifiManager.disconnect()) {
        // mWifiManager.setWifiEnabled(true);
        // System.out.println("wifi打开成功!!");
        // }
    }

    // 关闭WIFI
    public void closeWifi() {
        if (mWifiManager.isWifiEnabled()) {
            mWifiManager.setWifiEnabled(false);
        }
    }

    public boolean isWifiEnabled() {
        return mWifiManager.isWifiEnabled();
    }

    // 检查当前WIFI状态
    public int checkState() {
        return mWifiManager.getWifiState();
    }

    // 锁定WifiLock
    public void acquireWifiLock() {
        mWifiLock.acquire();
    }

    // 解锁WifiLock
    public void releaseWifiLock() {
        // 判断时候锁定
        if (mWifiLock.isHeld()) {
            mWifiLock.acquire();
        }
    }

    // 创建一个WifiLock
    public void creatWifiLock() {
        mWifiLock = mWifiManager.createWifiLock("Test");
    }

    // 得到配置好的网络
    public List<WifiConfiguration> getConfiguration() {
        return mWifiConfiguration;
    }

    // 指定配置好的网络进行连接
    public void connectConfiguration(int index) {
        // 索引大于配置好的网络索引返回
        if (index > mWifiConfiguration.size()) {
            System.out.println("连接失败!");
            return;
        }
        // 连接配置好的指定ID的网络
        mWifiManager.enableNetwork(mWifiConfiguration.get(index).networkId,
                true);
        System.out.println(index + "连接成功!");
    }

    public boolean connectConfiguration(String ssid) {
        String quotSsid = "\"" + ssid + "\"";
        boolean found = false;
        for (int i = 0; i < mWifiConfiguration.size(); i ++) {
            WifiConfiguration wifiConfiguration = mWifiConfiguration.get(i);
            String wifiSSID = wifiConfiguration.SSID;
            if (wifiSSID.equals(ssid) || wifiSSID.equals(quotSsid)) {
                found = mWifiManager.enableNetwork(mWifiConfiguration.get(i).networkId, true);
                break;
            }
        }
        return found;
    }

    public void startScan() {
        mWifiManager.startScan();
        // 得到扫描结果
        mWifiList = mWifiManager.getScanResults();
        // 得到配置好的网络连接
        mWifiConfiguration = mWifiManager.getConfiguredNetworks();
    }

    // 得到网络列表
    public List<ScanResult> getScanResults() {
        return mWifiList;
    }

    // 查看扫描结果
    public StringBuilder lookUpScan() {
        StringBuilder stringBuilder = new StringBuilder();
        for (int i = 0; i < mWifiList.size(); i++) {
            stringBuilder
                    .append("Index_" + new Integer(i + 1).toString() + ":");
            // 将ScanResult信息转换成一个字符串包
            // 其中把包括：BSSID、SSID、capabilities、frequency、level
            stringBuilder.append((mWifiList.get(i)).toString());
            stringBuilder.append("/n");
        }
        return stringBuilder;
    }

    // 得到MAC地址
    public String getMacAddress() {
        return (mWifiInfo == null) ? "NULL" : mWifiInfo.getMacAddress();
    }

    public String getSSID() {
        return (mWifiInfo == null) ? "NULL" : mWifiInfo.getSSID();
    }

    // 得到接入点的BSSID
    public String getBSSID() {
        return (mWifiInfo == null) ? "NULL" : mWifiInfo.getBSSID();
    }

    // 得到IP地址
    public int getIPAddress() {
        return (mWifiInfo == null) ? 0 : mWifiInfo.getIpAddress();
    }

    // 得到连接的ID
    public int getNetworkId() {
        return (mWifiInfo == null) ? 0 : mWifiInfo.getNetworkId();
    }

    // 得到WifiInfo的所有信息包
    public String getWifiInfo() {
        return (mWifiInfo == null) ? "NULL" : mWifiInfo.toString();
    }

    // 添加一个网络并连接
    public void addNetwork(WifiConfiguration wcg) {
        int wcgID = mWifiManager.addNetwork(wcg);
        boolean b =  mWifiManager.enableNetwork(wcgID, true);
        System.out.println("a--" + wcgID);
        System.out.println("b--" + b);
    }

    // 断开指定ID的网络
    public void disconnectWifi(int netId) {
        mWifiManager.disableNetwork(netId);
        mWifiManager.disconnect();
    }

    //然后是一个实际应用方法，只验证过没有密码的情况：
    public WifiConfiguration CreateWifiInfo(String SSID, String Password, int Type)
    {
        WifiConfiguration config = new WifiConfiguration();
        config.allowedAuthAlgorithms.clear();
        config.allowedGroupCiphers.clear();
        config.allowedKeyManagement.clear();
        config.allowedPairwiseCiphers.clear();
        config.allowedProtocols.clear();
        //config.SSID = "\"" + SSID + "\"";
        config.SSID = SSID;

        WifiConfiguration tempConfig = this.IsExsits(SSID);
        if(tempConfig != null) {
            mWifiManager.removeNetwork(tempConfig.networkId);
        }

        if(Type == 1) //WIFICIPHER_NOPASS
        {
            config.wepKeys[0] = "";
            config.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.NONE);
            config.wepTxKeyIndex = 0;
        }
        if(Type == 2) //WIFICIPHER_WEP
        {
            config.hiddenSSID = true;
            config.wepKeys[0]= "\""+Password+"\"";
            config.allowedAuthAlgorithms.set(WifiConfiguration.AuthAlgorithm.SHARED);
            config.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.CCMP);
            config.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.TKIP);
            config.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.WEP40);
            config.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.WEP104);
            config.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.NONE);
            config.wepTxKeyIndex = 0;
        }
        if(Type == 3) //WIFICIPHER_WPA
        {
            config.preSharedKey = "\""+Password+"\"";
            config.hiddenSSID = true;
            config.allowedAuthAlgorithms.set(WifiConfiguration.AuthAlgorithm.OPEN);
            config.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.TKIP);
            config.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.WPA_PSK);
            config.allowedPairwiseCiphers.set(WifiConfiguration.PairwiseCipher.TKIP);
            //config.allowedProtocols.set(WifiConfiguration.Protocol.WPA);
            config.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.CCMP);
            config.allowedPairwiseCiphers.set(WifiConfiguration.PairwiseCipher.CCMP);
            config.status = WifiConfiguration.Status.ENABLED;
        }
        return config;
    }

    private WifiConfiguration IsExsits(String SSID)
    {
        List<WifiConfiguration> existingConfigs = mWifiManager.getConfiguredNetworks();
        for (WifiConfiguration existingConfig : existingConfigs)
        {
            if (existingConfig.SSID.equals("\""+SSID+"\""))
            {
                return existingConfig;
            }
        }
        return null;
    }

    public List<String> getConfigedWifiList() {
        List<String> ssidList = new ArrayList<>();
        if (mWifiConfiguration != null) {
            for (WifiConfiguration config : mWifiConfiguration) {
                ssidList.add(trimSsid(config.SSID));
            }
        }
        return ssidList;
    }


    public List<String> getWifiList() {
        List<String> wifiList = getScanedWifiList();

        if (mWifiConfiguration != null) {
            for (WifiConfiguration config : mWifiConfiguration) {
                String ssid = trimSsid(config.SSID);
                if (!wifiList.contains(ssid)) {
                    wifiList.add(ssid);
                }
            }
        }

        return wifiList;
    }

    public List<String> getScanedWifiList() {
        List<String> ssidList = new ArrayList<>();
        for (ScanResult result: mWifiList) {
            ssidList.add(trimSsid(result.SSID));
        }
        return ssidList;
    }

    public static String trimSsid(String ssid) {
        if (ssid.startsWith("\"")) {
            ssid = ssid.substring(1, ssid.length()-1);
        }
        return ssid;
    }

    public ScanResult findWifi(String ssid) {
        for (ScanResult result: mWifiList) {
            if (ssid.equals(trimSsid(result.SSID))) {
                return result;
            }
        }
        return null;
    }

    public boolean isConfiged(String ssid) {
        if (mWifiConfiguration == null) {
            return false;
        }

        for (WifiConfiguration config : mWifiConfiguration) {
            if (ssid.equals(trimSsid(config.SSID))) {
                return true;
            }
        }
        return false;
    }

    public boolean removeConfiguration(String ssid) {
        boolean removed = false;
        WifiConfiguration tempConfig = this.IsExsits(ssid);
        if(tempConfig != null) {
            removed = mWifiManager.removeNetwork(tempConfig.networkId);
            mWifiManager.saveConfiguration();
        }
        return removed;
    }

    public boolean connectWifi(String ssid) {
        if (isConfiged(ssid)) {
            return connectConfiguration(ssid);
        }

        boolean found = false;
        ScanResult result = findWifi(ssid);
        if (result == null) {
            return false;
        }

        return ConnectionUnConfigForNoPsw(ssid);
    }

    public boolean ConnectionUnConfigForNoPsw(String ssid)
    {
        try
        {
            WifiConfiguration wc = new WifiConfiguration();

            wc.hiddenSSID = false;
            wc.status = WifiConfiguration.Status.ENABLED;

//            wc.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.WPA_PSK);
//            wc.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.WPA_EAP);

            wc.allowedProtocols.set(WifiConfiguration.Protocol.WPA);
            wc.allowedProtocols.set(WifiConfiguration.Protocol.RSN);

            wc.allowedPairwiseCiphers.set(WifiConfiguration.PairwiseCipher.TKIP);
            wc.allowedPairwiseCiphers.set(WifiConfiguration.PairwiseCipher.CCMP);

            wc.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.WEP40);
            wc.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.WEP104);
            wc.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.TKIP);
            wc.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.CCMP);

            wc.SSID = "\"" + ssid + "\"";
            wc.preSharedKey = null;

            wc.BSSID = "any";
            wc.priority = 10;

            //wc.wepKeys[0] = "";
            wc.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.NONE);
            wc.wepTxKeyIndex = 0;

            int res = mWifiManager.addNetwork(wc);
            boolean done = mWifiManager.enableNetwork(res, true);
            mWifiManager.saveConfiguration();
            return done;
        }
        catch(Exception ex)
        {
            return false;
        }
    }

}